package comits.web.client.servlets.gestion.drp;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.servlet.ServletUtilities;

import comits.business.tiers.dao.PrevisionDAO;
import comits.business.tiers.dao.PrevisionDAOImpl;
import comits.business.tiers.metiers.Boutique;
import comits.business.tiers.metiers.Prevision;

public class PrevGraphServlet extends HttpServlet
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void service (HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
	{
	       

    	HttpSession session = request.getSession(); 
		if (session.getAttribute("connexion")== null){
			RequestDispatcher disp=getServletContext().getRequestDispatcher("/index.jsp");
			disp.forward(request,response);
		}
    	
    	int btqN =Integer.parseInt(request.getParameter("btq"));
    	String typChart = request.getParameter("typeChart");
    	String btqNom = getNomBtq(btqN,session);
		PrevisionDAO pDao = new PrevisionDAOImpl();
		if(typChart==null) typChart ="curve";
		JFreeChart jfreechart = BarChart.createChart(btqN,typChart,btqNom) ;
 
                ChartRenderingInfo chartRenderingInfo = new ChartRenderingInfo(new StandardEntityCollection());
 
                int largeur = 650 ;
                int hauteur = 450 ;
 
		String filename = ServletUtilities.saveChartAsPNG(jfreechart, largeur, hauteur, chartRenderingInfo, request.getSession());
 
		Graphe graphe = this.initImage(request, chartRenderingInfo, filename);
 
		request.setAttribute("graphe",graphe) ;
		request.setAttribute("data",pDao.getListPrevGraph(btqN));
 
		RequestDispatcher disp=getServletContext().getRequestDispatcher("/prevision.jsp");
		disp.forward(request,response) ;
	}
	
	private String getNomBtq(int btqN, HttpSession session) {
		List<Boutique> lstC = (List<Boutique>) session.getAttribute("listBtq");
		for (int i = 0; i < lstC.size(); i++){
			if(lstC.get(i).getNumBtq()==btqN) return lstC.get(i).getLibelleBtq();
		}
		return "";
	}

	private Graphe initImage(HttpServletRequest request,ChartRenderingInfo chartRenderingInfo, String filename)
	{
		String map = ChartUtilities.getImageMap(filename, chartRenderingInfo);
		String src = request.getContextPath()+"/DisplayChart?filename=" + filename ;
		String useMap = "#" + filename  ;
 
		Graphe graphe = new Graphe() ;
		graphe.setMap(map);
		graphe.setSrc(src) ;
		graphe.setUseMap(useMap) ;
 
		return graphe ;
	}
}